<?php
namespace app\admin\validate;

/**
 * 用户验证
 */
class Role extends Main
{
    protected $rule = [
        'id' => 'require',
        'title' => 'require',
        'permission_ids' => 'require|checkPermission',
        'del' => 'require|checkDel',
        'site_id' =>'require|checkSite'
    ];

    protected $message = [
        'id.require' => '请选择要编辑的角色',
        'title.require' => '请填写角色名',
        'permission_ids.require' => '请选择权限',
        'site_id.require' => '请选择站点'
    ];

    protected $scene = [
        'add' =>  ['title', 'permission_ids', 'site_id'],
        'edit' => ['id', 'title', 'permission_ids', 'site_id'],
        'del' => ['id']
    ];

    protected function checkPermission($value)
    {
        if(!is_array($value)){
            $value = [$value];
        }
        $permissionIds = (new \app\admin\model\Permission)->where('id', 'in', $value)->column('id');
        if(count($permissionIds) != count($value)){
            return '权限参数错误';
        }
        return true;
    }

    protected function checkDel($value, $rule, $data = [])
    {
        //查询角色是否关联了用户
        $admin = \think\Db::name('admin')->field('role_id')->select()->toArray();
        foreach($admin as $v){
            $temp = json_decode($v['role_ids'], true);
            foreach($data['id'] as $v1){
                if(in_array($v1, $temp)){
                    return '角色已授权给用户，请先删除用户或修改用户角色';
                }
            }
        }
        return true;
    }

    protected function checkSite($value)
    {
        $site = \think\Db::name('site')->where('id', $value)->value('id');
        if(!$site){
            return '站点不存在';
        }
        return true;
    }
}